import request from "./useRequests";
import { userinfo } from '@/stores/counter'
import { ElMessage } from 'element-plus'

export default function getNewsByConditon() {
    const user = userinfo()
    async function searchContent(isHot: boolean, ids: number[], keywords: string) {
        const page = user.pages.search.page
        if (page == 1) user.pages.search.list = []
        try {
            const res = await request({
                method: "get",
                url: `/news/getNewsByConditon`,
                params: {
                    'isHot': isHot,
                    'ids': ids.join(','),
                    'keywords': keywords,
                    'page': page,
                    'limit': 6
                }
            })
            if(!res.data.success) {
                throw new Error("搜索出现错误")
            }
            return res.data
        } catch (err: any) {
            ElMessage({
                message: err,
                type: 'error',
            })
        }
    }
    async function searchArticle(keywords: string) {
        const page = user.pages.search.page
        if (page == 1) user.pages.search.list = []
        try {
            const res = await request({
                method: "get",
                url: `/news/search`,
                params: {
                    "keywords": keywords,
                    "page": page,
                    "limit": 6
                }
            })
            return res.data
        } catch (err: any) {
            //alert(err)
        }
    }
    async function searchFullText(searchTerm: string) {
        const page = user.pages.search.page
        if (page == 1) user.pages.search.list = []
        try {
            const res = await request({
                method: "post",
                url: `/search`,
                data: {
                    searchTerm: searchTerm,
                }
            })
            return res.data
        } catch (err: any) {
            //alert(err)
        }
    }

    return {
        searchContent, searchArticle, fullTextSearch: searchFullText
    }
}